package api

import (
	"github.com/gin-gonic/gin"
	"log"
	"oidc/dao"
	"oidc/model"
	"oidc/util"
)

func ReturnAccToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		var req model.AccessTokenReq

		req.GrantType = c.PostForm(util.GetCode(util.GRANT_TYPE))
		req.Code = c.PostForm(util.GetCode(util.CODE))
		req.RedirectUrl = c.PostForm(util.GetCode(util.REDIRECT_URL))
		req.ClientId = c.PostForm(util.GetCode(util.CLIENT_ID))
		req.ClientSecret = c.PostForm(util.GetCode(util.CLIENT_SECRET))

		var client model.Client
		client.ClientID = req.ClientId
		client.ClientSecret = req.ClientSecret
		client.RedirectUrl = req.RedirectUrl

		if !dao.IFClientSecretRight(client) {
			c.JSON(200, gin.H{
				"status": false,
				"data":   "parm is not right",
			})
			return
		}

		userAuth, err := dao.QueryUserAuth(req.Code)
		if err != nil {
			log.Println(err)
			c.JSON(401, gin.H{
				"status": false,
				"data":   err.Error(),
			})
			return
		}

		if userAuth.ClientId != req.ClientId {
			log.Println("得到一个错误的client id")
			c.JSON(401, gin.H{
				"status": false,
				"data":   "client_id不正确",
			})
			return
		}

		tokenDb := &dao.TokenDB
		are, err := tokenDb.CreateARIToken(userAuth) //存储aToken和人rToken到本地
		//(aToken有过期时间,rToken是一个uuid)
		if err != nil {
			log.Println(err)
			return
		}

		res := model.AccessTokenResp{
			AccessToken:  are.AToken,
			RefreshToken: are.RToken,
			ExpiresIn:    are.ExTime,
			IdToken:      are.IdToken,
		}

		c.JSON(200, res)
	}
}
